package com.yanxin.workflow.service.jaxrs.client;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.List;

public class ClientInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private String UserName;
    private String UserPass;

    public ClientInterceptor(String UserName, String UserPass)
    {
        super(Phase.PREPARE_SEND);
        this.UserName = UserName;
        this.UserPass = UserPass;
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {

        /**
         * List<Header> headers = message.getHeaders();
         *
         *         Document document = DOMUtils.createDocument();
         *
         *         Element name = document.createElement("ns1:username");
         *         name.setAttribute("xmlns:ns1","**");
         *         name.setTextContent("zz");
         *
         *         Element password = document.createElement("ns2:password");
         *
         *         password.setAttribute("xmlns:ns2","**");
         *         password.setTextContent("1");
         *
         *         headers.add(new Header(new QName(""),name));
         *         headers.add(new Header(new QName(""),password));
         */

        List<Header> headers = message.getHeaders();
        Document doc = DOMUtils.createDocument();
        Element auth = doc.createElementNS("http://tempuri.org/","SecurityHeader");
        Element UserName = doc.createElement("UserName");
        Element UserPass = doc.createElement("UserPass");

        UserName.setTextContent(this.UserName);
        UserPass.setTextContent(this.UserPass);

        auth.appendChild(UserName);
        auth.appendChild(UserPass);

        headers.add(0, new Header(new QName("SecurityHeader"),auth));
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getUserPass() {
        return UserPass;
    }

    public void setUserPass(String userPass) {
        UserPass = userPass;
    }
}
